package com.scu.phototabuser.ui.navitems;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scu.phototabuser.Consts;
import com.scu.phototabuser.MainDecisionMaker;
import com.scu.phototabuser.R;
import com.scu.phototabuser.data.source.local.User;
import com.scu.phototabuser.data.source.remote.Response;
import com.scu.phototabuser.http.OkHttp3Methods;
import com.scu.phototabuser.ui.taskgroup.ChooseGroupActivity;
import com.scu.phototabuser.ui.taskgroup.ImageType;
import com.scu.phototabuser.util.NetworkUtil;
import com.scu.phototabuser.util.Predictions;
import com.scu.phototabuser.util.PreferenceUtil;
import com.scu.phototabuser.util.ToastUtil;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.finalteam.rxgalleryfinal.RxGalleryFinal;
import cn.finalteam.rxgalleryfinal.imageloader.ImageLoaderType;
import cn.finalteam.rxgalleryfinal.rxbus.RxBusResultSubscriber;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageRadioResultEvent;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import mabbas007.tagsedittext.TagsEditText;

/**
 * Created by tianfei on 2017/5/10.
 */

public class MineDetailActivity extends AppCompatActivity
        implements View.OnClickListener, TagsEditText.TagsEditListener{

    public static final int REQUEST_FOR_EDIT_USER_INFO = 0x1101;

    @BindView(R.id.header_img) SimpleDraweeView header_img;
    @BindView(R.id.edit) TextView btn_edit;
    @BindView(R.id.btn_logout) Button btn_logout;
    @BindView(R.id.tv_name) TextView tv_name;
    @BindView(R.id.tv_sig) TextView tv_sig;
    @BindView(R.id.btn_add_types) ImageButton btn_add_types;
    @BindView(R.id.tagsEditText) TagsEditText mTagsEditText;

    private ProgressDialog progressDialog;
    private static final String TAG = "MineDetailActivity";

    //维护喜好Integer数组
    private static HashSet<Integer> userChosenTypeCode =new HashSet<>();
    //显示用户喜好标签
    private static HashSet<String> userChosenTypeString =new HashSet<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_detail);
        ButterKnife.bind(this);

        //设置状态栏透明
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

        // FIXME: 2017/5/22
        header_img.setOnClickListener(this);

        mTagsEditText.setHint(getString(R.string.no_type_selected));
        mTagsEditText.setTagsListener(this);
        mTagsEditText.setTagsWithSpacesEnabled(true);
//        mTagsEditText.setAdapter(new ArrayAdapter<>(this,
//                android.R.layout.simple_dropdown_item_1line, userChosenTypeString.toArray()));
        mTagsEditText.setThreshold(1);
        //设置不显示光标
        mTagsEditText.setCursorVisible(false);
        //设置为不获取焦点，禁止用户通过直接输入的方式更改喜好
        mTagsEditText.setFocusable(false);

        btn_add_types.setOnClickListener(this);
        header_img.setOnClickListener(this);
        btn_edit.setOnClickListener(this);
        btn_logout.setOnClickListener(this);
 //       tv_sig.setOnClickListener(this);

    }

    //重新加载信息
    @Override
    protected void onResume() {
        super.onResume();

        //没有网络连接的情况
        if (!NetworkUtil.isNetworkAviliable(this)){
            User user=PreferenceUtil.getSavedUser();
            // FIXME: 2017/5/21 加载本地用户头像
            //header_img.setImageURI(user.getHeaderUrl());
            ToastUtil.makeToast(MineDetailActivity.this,getString(R.string.network_not_available));
            tv_name.setText(user.getName());
            tv_sig.setText(user.getSignature());
            return;
        }

        progressDialog=new ProgressDialog(this,R.style.TransparentProgressDialog);
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(true);
        progressDialog.setMessage("Loading...");
        progressDialog.show();

        loadUserTags();
        loadUserMsg();

        String[] temp=new String[userChosenTypeString.size()];
        userChosenTypeString.toArray(temp);
        mTagsEditText.setTags(temp);
        progressDialog.cancel();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //存储修改过的用户喜好信息
        Integer[] arr=new Integer[userChosenTypeCode.size()];
        userChosenTypeCode.toArray(arr);
        PreferenceUtil.saveUserChosenTypes(Predictions.parseStringFromUserTypeArray(arr));
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_FOR_EDIT_USER_INFO){
            Log.d("MineDetailActivity:", "onActivityResult: "+requestCode);
            header_img.setImageURI(Consts.mUser.getHeaderUrl());
            tv_name.setText(Consts.mUser.getName());
            tv_sig.setText(Consts.mUser.getSignature());
        }
    }

    //加载保存的用户喜好信息
    private void loadUserTags() {
        String s=PreferenceUtil.getUserChosenTypes();
        if (TextUtils.isEmpty(s)){
            return;
        }
        int[] types=Predictions.getUserTypeArrayFromString(s);
        for (int i:types){
            String msg= ImageType.getMsgFromType(i);
            userChosenTypeCode.add(i);
            userChosenTypeString.add(msg);
        }
    }
    //检查服务器  /token/info 用户信息是否改变
    //   对于用户头像，检查服务器返回的图片id是否不一致
    private void loadUserMsg(){

        Observable.create(new ObservableOnSubscribe<User>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<User> e) throws Exception {

                String json=
                        OkHttp3Methods.PostRequestWithToken(Consts.QueryUserInfoURL,null);

                if (TextUtils.isEmpty(json)){
                    e.onError(new RuntimeException("Server No Response!"));
                }

                Response<User> response = new Gson().fromJson(json,
                        new TypeToken<Response<User>>(){}.getType());

                if (response.getCode()!=200){
                    e.onError(new RuntimeException(response.getMessage()));
                }

                User user=response.getData();

                //在Consts中保存当前用户的信息
                // FIXME: 2017/5/13 修改对象复制方法
                Consts.mUser.setId(user.getId());
                Consts.mUser.setEmail(user.getEmail());
                Consts.mUser.setHeaderUrl(user.getHeaderUrl());
                Consts.mUser.setName(user.getName());
                Consts.mUser.setSignature(user.getSignature());

                //在Preference中保存用户信息
                PreferenceUtil.saveUserInfo(user);

                e.onNext(user);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<User>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {}

            @Override
            public void onNext(@NonNull User user) {
                header_img.setImageURI(user.getHeaderUrl());
                tv_name.setText(user.getName());
                tv_sig.setText(user.getSignature());
            }

            @Override
            public void onError(@NonNull Throwable e) {
                ToastUtil.makeToast(MineDetailActivity.this,e.getMessage());
            }

            @Override
            public void onComplete() {}
        });

    }

    @Override
    public void onTagsChanged(Collection<String> tags) {
//        Log.d(TAG, "Tags changed: ");
//        Log.d(TAG, Arrays.toString(tags.toArray()));
        //onBackPressed();

        //更改数据显示
        userChosenTypeString.clear();
        userChosenTypeString.addAll(tags);

        //更新存储值
        userChosenTypeCode.clear();
        for (String s:tags){
            userChosenTypeCode.add(ImageType.getIntFromMsg(s));
        }

        Log.d(TAG, "onTagsChanged: userChosenTypeString:"+ userChosenTypeString.toString());
    }

    @Override
    public void onEditingFinished() {
        Log.d(TAG,"OnEditing finished");
        //不做任何实现
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.header_img:
                // FIXME: 2017/5/12 选择图片选择器框架
                //单选图片
                RxGalleryFinal
                        .with(MineDetailActivity.this)
                        .image()
                        //.radio()
                        .crop()
                        .cropMaxBitmapSize(100)
                        .cropOvalDimmedLayer(true)
                        .imageLoader(ImageLoaderType.PICASSO)
                        .subscribe(new RxBusResultSubscriber<ImageRadioResultEvent>() {
                            @Override
                            protected void onEvent(ImageRadioResultEvent imageRadioResultEvent) throws Exception {
                                //Toast.makeText(getBaseContext(), "选中了图片路径："+imageRadioResultEvent.getResult().getOriginalPath(), Toast.LENGTH_SHORT).show();

                                Log.e(TAG, "onEvent: onEvent"+imageRadioResultEvent.getResult().getCropPath());
                            }
                        }).openGallery();

                break;
            case R.id.tv_name:

                break;
            //添加用户喜好
            case R.id.btn_add_types:
                Intent i2ChoseType = new Intent(this, ChooseGroupActivity.class);
                i2ChoseType.putExtra(Consts.ACTION_MINEDETAIL_CHANGE_USER_CHOSEN_TYPE,true);
                startActivity(i2ChoseType);
                break;
            case R.id.edit:
                Intent i2EditList = new Intent(MineDetailActivity.this,EditListActivity.class);
                startActivityForResult(i2EditList,REQUEST_FOR_EDIT_USER_INFO);
                break;
            case R.id.btn_logout:
                ProgressDialog dialog=new ProgressDialog(this,
                        R.style.TransparentProgressDialog);
                dialog.setMessage("uploading...");
                dialog.setIndeterminate(true);
                dialog.setCancelable(false);
                dialog.show();

                doLogout(dialog);

                dialog.cancel();
                //Log.e("eeeeee", "onClick: "+"it come to here!!!!!!!!!!!!!");
                break;
            default:break;
        }
    }

    private void doLogout(final ProgressDialog d) {
        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Boolean> e) throws Exception {
                String json = OkHttp3Methods.PostRequestWithToken(Consts.LogoutURL,null);

                Response response=new Gson().fromJson(json,Response.class);

                if (response.getCode() == 200){
                    e.onNext(true);
                }else {
                    e.onError(new RuntimeException(response.getMessage()));
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {}

            @Override
            public void onNext(@NonNull Boolean aBoolean) {

//                if (!aBoolean){
//                    //doSomething
//                }

                // 清空保存状态
                PreferenceUtil.clearPreferenceState();
                //fixme 回收、释放所有资源
                //do clean here

                d.cancel();

                Intent i2Start = new Intent(MineDetailActivity.this, MainDecisionMaker.class);
                i2Start.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i2Start);
            }

            @Override
            public void onError(@NonNull Throwable e) {
                ToastUtil.makeToast(MineDetailActivity.this,e.getMessage());
            }

            @Override
            public void onComplete() {}
        });
    }
}
